//
//  MainViewController.m
//  TestOCRedux
//
//  Created by Hotacool on 2019/2/25.
//  Copyright © 2019 Hotacool. All rights reserved.
//

#import "MainViewController.h"
#import "HStore.h"
#import "HState.h"
#import "AppActions.h"
#import "AppDelegate.h"
#import "Product.h"
#import "StepRecord.h"

#define kstore ((AppDelegate*)[UIApplication sharedApplication].delegate).store
static int kButtonTag = 1000;
static const CGFloat kMarginVertical = 15.0;
static const CGFloat kSpacingH = 5.0;
@interface MainViewController () <HSubscriberType, UITableViewDelegate, UITableViewDataSource>
@property (nonatomic, strong) UILabel *remainLabel;
@property (nonatomic, strong) UILabel *eatLabel;

@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) NSArray *items;
@end

@implementation MainViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    _remainLabel = [[UILabel alloc] initWithFrame:CGRectMake(kMarginVertical, 100, self.view.frame.size.width - kMarginVertical*2, 40)];
    _remainLabel.backgroundColor = [UIColor groupTableViewBackgroundColor];
    _remainLabel.textAlignment = NSTextAlignmentLeft;
    _remainLabel.textColor = [UIColor greenColor];
    _remainLabel.font = [UIFont systemFontOfSize:24];
    [self.view addSubview:_remainLabel];
    _eatLabel = [[UILabel alloc] initWithFrame:CGRectMake(kMarginVertical, CGRectGetMaxY(_remainLabel.frame)+kSpacingH*2, self.view.frame.size.width - kMarginVertical*2, 60)];
    _eatLabel.backgroundColor = [UIColor groupTableViewBackgroundColor];
    _eatLabel.textAlignment = NSTextAlignmentCenter;
    _eatLabel.textColor = [UIColor redColor];
    _eatLabel.font = [UIFont systemFontOfSize:34];
    [self.view addSubview:_eatLabel];
    
    UIButton *btn;
    CGFloat originY = CGRectGetMaxY(_eatLabel.frame) + 2*kSpacingH;
    for (int i = 0; i < 5; i++) {
        btn = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, (self.view.frame.size.width - 2*kMarginVertical - 40)/2, 50)];
        btn.backgroundColor = [UIColor groupTableViewBackgroundColor];
        [btn setTitleColor:[UIColor blueColor] forState:UIControlStateNormal];
        btn.tag = kButtonTag + i;
        [self.view addSubview:btn];
        if (i % 2 == 1) {
            btn.center = CGPointMake(self.view.frame.size.width - btn.frame.size.width/2 - kMarginVertical, originY+btn.frame.size.height/2);
            originY += (btn.frame.size.height + kSpacingH);
        } else {
            btn.center = CGPointMake(kMarginVertical + btn.frame.size.width/2, originY+btn.frame.size.height/2);
        }
        [btn addTarget:self action:@selector(click:) forControlEvents:UIControlEventTouchUpInside];
        switch (i) {
            case 0: {
                [btn setTitle:@"eat" forState:UIControlStateNormal];
                break;
            }
            case 1: {
                [btn setTitle:@"add" forState:UIControlStateNormal];
                break;
            }
            case 2: {
                [btn setTitle:@"reset" forState:UIControlStateNormal];
                break;
            }
            case 3: {
                [btn setTitle:@"auto add" forState:UIControlStateNormal];
                break;
            }
            case 4: {
                [btn setTitle:@"record" forState:UIControlStateNormal];
                break;
            }
        }
    }
    UIView *line = [[UIView alloc] initWithFrame:CGRectMake(2, CGRectGetMaxY(btn.frame) + 4, self.view.frame.size.width - 4, 1)];
    line.backgroundColor = [UIColor blackColor];
    [self.view addSubview:line];
    _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, CGRectGetMaxY(line.frame), self.view.frame.size.width, self.view.frame.size.height - CGRectGetMaxY(line.frame)) style:UITableViewStylePlain];
    _tableView.delegate = self;
    _tableView.dataSource = self;
    [self.view addSubview:_tableView];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [kstore subscribe:self specifySubState:NSStringFromClass([Product class])];
    [kstore subscribe:self specifySubState:@"StepRecord"];
    fetchProductAction(kstore);
}

- (void)click:(UIButton*)sender {
    switch (sender.tag - kButtonTag) {
        case 0:
            [kstore dispatch:[HAction actionWithType:kEatAction payload:@(1)]];
            break;
        case 1:
            [kstore dispatch:[HAction actionWithType:kAddAction payload:@(2)]];
            break;
        case 2:
            fetchProductAction(kstore);
            break;
        case 3:
            autoEatAction(kstore);
            break;
        case 4:
            recordAction(kstore, kstore.state[@"Product"]);
            break;
        default:
            break;
    }
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.items.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cellid"];
    if (!cell) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"cellid"];
    }
    cell.textLabel.text = [NSString stringWithFormat:@"Step_%ld", indexPath.row];
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView reloadData];
    UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
    cell.textLabel.text = [NSString stringWithFormat:@"Step_%ld selected!", indexPath.row];
    jumpToStepAction(kstore, self.items[indexPath.row]);
}

#pragma mark - HSubscriberType
- (void)stateChanged:(id)newState action:(id<HActionType>)action{
    NSLog(@"newState: %@, action:%@", newState, action.type);
    if ([newState isKindOfClass:[Product class]]) {
        Product *p = newState;
        self.remainLabel.text = [NSString stringWithFormat:@"Remain: %lu", p.count - p.consume];
        self.eatLabel.text = [NSString stringWithFormat:@"consumed: %lu", (unsigned long)p.consume];
    } else if ([newState isKindOfClass:[StepRecord class]]) {
        StepRecord *sr = newState;
        NSLog(@"StepRecord: %ld", sr.steps.count);
        self.items = sr.steps;
        
        [self.tableView reloadData];
    }
}
@end
